<?php
namespace app\Common\command;

use app\admin\model\Admin;
use app\massage\model\Bonus;
use app\massage\model\Coach;
use app\massage\model\CoachLevel;
use app\massage\model\GroupRatio;
use app\massage\model\Identity;
use app\massage\model\Order;
use app\massage\model\StoreList;
use app\massage\model\User;
use app\massage\model\UserGroup;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

/**
 * 招商订单分润
 */
class ServiceBonus extends Command
{
    protected $order_model;
    protected $coach_model;
    protected $coach_level_model;
    protected $identity_model;
    protected $user_model;
    protected $bonus_model;
    protected $group_model;
    protected $group_ratio_model;
    protected $store_model;
    protected $admin_model;

    public function __construct() {

        parent::__construct();
        $this->order_model = new Order();
        $this->coach_model = new Coach();
        $this->coach_level_model = new CoachLevel();
        $this->identity_model = new Identity();
        $this->user_model = new User();
        $this->bonus_model = new Bonus();
        $this->group_model = new UserGroup();
        $this->group_ratio_model = new GroupRatio();
        $this->store_model = new StoreList();
        $this->admin_model = new Admin();
    }
    protected function configure()
    {
        $this->setName('service_bonus')->setDescription('服务订单分润');
    }

    //执行
    protected function execute(Input $input, Output $output)
    {
        $where = [
            'pay_type' => 7,
            'handle_status' => 0,
        ];
        $order_lists = $this->order_model->where($where)->select();
        if(!count($order_lists)){
            $output->writeln('服务订单分润完成。已处理：0');
        }
        $order_lists = $order_lists->toArray();
        Db::startTrans();
        try {
            foreach ($order_lists as $order) {
                //1.自己分润
                $left_amount = $this->handleSelf($order);
                if($left_amount <= 0){
                    break;
                }
                //2.门店抽佣（剩余金额不能分成负数）
                $store_left_amount = $this->handleStore($order,$left_amount);
                if($store_left_amount <= 0){
                    break;
                }
                //3.按身份分红 4.师徒感恩奖
                $identity_left_amount = $this->handleIdentity($order,$left_amount,$store_left_amount);
            }
            //修改招商订单状态为：已处理
            $order_ids = array_column($order_lists,'id');
            $where = [
                ['id','in',$order_ids],
                ['handle_status','=',0]
            ];
            $this->order_model->where($where)->update(['handle_status' => 1]);
        }catch(\Exception $e){
            Db::rollback();
            $output->writeln('服务订单分润执行出错：'.$e->getFile()."\n".$e->getLine()."\n".$e->getMessage());
        }
        Db::commit();
        $output->writeln('服务订单分润完成。已处理：'.count($order_lists));
    }

    //门店分润
    protected function handleSelf($order)
    {
        $total_amount = $order['pay_price'];
        $coach = $this->coach_model->dataInfo(['id' => $order['coach_id']]);
        if(empty($coach)){
            return $total_amount;
        }
        $user = $this->user_model->dataInfo(['id' => $coach['user_id']]);
        if(empty($user)){
            return $total_amount;
        }
        $coach_level = $this->coach_level_model->dataInfo(['id' => $user['coach_level_id']]);
        if(empty($coach_level)){
            return $total_amount;
        }
        $self_ratio = $coach_level['balance'];
        $bonus = round($total_amount * $self_ratio,2);
        $bonus_data = [
            'user_id' => $user['id'],
            'relation_id' => $order['id'],
            'type' => 10,
            'bonus' => $bonus,
            'send_status' => 0,
            'create_time' => time(),
        ];
        $this->bonus_model->insert($bonus_data);
        return $total_amount - $bonus;
    }

    //门店抽佣
    protected function handleStore($order,$left_amount)
    {
        $coach = $this->coach_model->dataInfo(['id' => $order['coach_id']]);
        if(empty($coach)){
            return $left_amount;
        }
        $store = $this->store_model->dataInfo(['id' => $coach['store_id']]);
        if(empty($store)){
            return $left_amount;
        }
        $admin = $this->admin_model->dataInfo(['id' => $store['admin_id']]);
        if(empty($admin)){
            return $left_amount;
        }
        $user = $this->user_model->dataInfo(['id' => $admin['user_id']]);
        if(empty($user)){
            return $left_amount;
        }
        $identity = $this->identity_model->dataInfo(['id' => $user['identity_id']]);
        if(empty($identity)){
            return $left_amount;
        }
        $rule = $identity['rule'] ? json_decode($identity['rule']) : [];
        if(empty($rule)){
            return $left_amount;
        }
        $ratio = 0;
        foreach ($rule as $item) {
            if($item['type_id'] == 5){
                $ratio = $item['ratio'];
                if(isset($item['form']) && $item['form'] == 1){
                    $left_amount = $order['amount'];
                }
            }
        }
        if(!$ratio){
            return $left_amount;
        }
        $bonus = round($left_amount * $ratio,2);
        $bonus_data = [
            'user_id' => $user['id'],
            'relation_id' => $order['id'],
            'type' => 5,
            'bonus' => $bonus,
            'send_status' => 0,
            'create_time' => time(),
        ];
        $this->bonus_model->insert($bonus_data);
        return $left_amount - $bonus;
    }

    //按身份分红
    protected function handleIdentity($order,$left_amount,$store_left_amount)
    {
        $coach = $this->coach_model->dataInfo(['id' => $order['coach_id']]);
        if(empty($coach)){
            return $left_amount;
        }
        $user = $this->user_model->dataInfo(['id' => $coach['user_id']]);
        if(empty($user)){
            return $left_amount;
        }
        $parent = $this->user_model->where(['id' => $user['pid']])->find();
        if(!$parent['identity_id']){
            return true;
        }
        $identity = $this->identity_model->dataInfo(['id' => $parent['identity_id']]);
        if(empty($identity)){
            return $left_amount;
        }
        $rule = $identity['rule'] ? json_decode($identity['rule']) : [];
        if(empty($rule)){
            return $left_amount;
        }
        $ratio = 0;
        foreach ($rule as $item) {
            if($item['type_id'] == 10){
                $ratio = $item['ratio'];
                if(isset($item['form']) && $item['form'] == 1){
                    $left_amount = $order['amount'];
                }
                break;
            }
        }
        if(!$ratio){
            return $left_amount;
        }
        //按身份分红
        $bonus = round($left_amount * $ratio,2);
        $bonus_data = [
            'user_id' => $parent['id'],
            'relation_id' => $order['id'],
            'type' => 10,
            'bonus' => $bonus,
            'send_status' => 0,
            'create_time' => time(),
        ];
        $this->bonus_model->insert($bonus_data);
        $left_amount = $left_amount - $bonus - $store_left_amount;
        if($left_amount <= 0){
            return $left_amount;
        }
        if($identity['type'] == 1){
            $master_ratio = 0;
            foreach ($rule as $item) {
                if($item['type_id'] == 7){
                    $master_ratio = $item['ratio'];
                }
            }
            //按师徒感恩比例分红
            $bonus = round($left_amount * $master_ratio,2);
            $bonus_data = [
                'user_id' => $parent['id'],
                'relation_id' => $order['id'],
                'type' => 7,
                'bonus' => $bonus,
                'send_status' => 0,
                'create_time' => time(),
            ];
            $this->bonus_model->insert($bonus_data);
        }
    }
}